package com.aruba.socketlibrary.entity;


import com.aruba.socketlibrary.protocol.FileManger;

/**
 * Created by aruba on 2017/10/20.
 */

public class SerialFile extends SerialFileBase {
    /**
     * 包索引 4bytes
     */
    private long packetIndex;
    /**
     * 本包数据长度 2bytes
     */
    private int packetLength;
    /**
     * 当前桢数据内容
     */
    private byte[] data;

    /**
     * 文件索引bytes
     */
    private byte[] packetIndexBytes = new byte[4];

    public long getPacketIndex() {
        return packetIndex;
    }

    public void setPacketIndex(long packetIndex) {
        this.packetIndex = packetIndex;
    }

    public byte[] getPacketIndexBytes() {
        return packetIndexBytes;
    }

    public void setPacketIndexBytes(int index, byte b) throws Exception {
        if (index < 4 && index >= 0)
            packetIndexBytes[index] = b;
        else
            throw new Exception("wtf");
    }

    public int getPacketLength() {
        return packetLength;
    }

    public void setPacketLength(int packetLength) {
        this.packetLength = packetLength;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public boolean parseData(byte[] realData, FileManger fileManger) throws Exception {
        parseData(realData);

        long packetIndex = 0;
        for (int i = 0; i < 4; i++) {
            packetIndex += packetIndex * 256 + (realData[3 + i + getFileNameLength()] & 0xFF);
            setPacketIndexBytes(i, realData[3 + i + getFileNameLength()]);
        }

        setPacketIndex(packetIndex);

        int packetength = (realData[getFileNameLength() + 7] & 0xFF) * 256 + realData[getFileNameLength() + 8];
        setPacketLength(packetength);

        byte[] data = new byte[packetength];
        System.arraycopy(realData, getFileNameLength() + 9, data, 0, data.length);
        setData(data);

        return true;
    }
}
